(ns packet.utils-test
  (:require [clojure.test :refer :all]
            [clojure.string :as str]
            [packet.utils :refer :all]))

(deftest utils-functions
  (testing "utils functions"
    (is (every? digit? "0123456789"))
    
    (are [i o] (= (bcd->byte i) o)
      0x00 0
      0x12 12
      0x98 98)
    
    (is (every? #(-> % byte->bcd bcd->byte (= %)) (range 100)))

    (are [i o] (= (str/lower-case (byte->hex i)) o)
      0x12 "12"
      0xab "ab")
    
    (is (every? #(-> % byte->hex hex->byte (= %)) (range 256)))

    (let [coll [1 2 :a :b]]
      (are [e n] (= (getf coll e) n)
        1 2
        2 :a
        :a :b
        :b nil
        :c nil))
    
    (are [i o] (= (bcd->byte i) o)
      0x01 1
      0x10 10
      0x99 99)
    
    (are [i o] (= (byte->bcd i) o)
      1 0x01
      10 0x10
      99 0x99)

    (are [i o] (= (byte->hex i) o)
      1 "01"
      0x10 "10"
      0x99 "99"
      0xab "ab")
    
    (are [i o] (= (hex->byte i) o)
      "01" 1
      "10" 0x10
      "99" 0x99
      "ab" 0xab)

    (are [i o] (= (hex-string->bytes i) o)
      "12345 67 89 ab cd" [1 0x23 0x45 0x67 0x89 0xab 0xcd])
    (are [i o] (= (bytes->hex-string i) o)
      [1 0x23 0x45 0x67 0x89 0xab 0xcd] "01 23 45 67 89 ab cd")

    (is (nil? (uint->bytes nil 0)))
    (is (= (uint->bytes 12 2) [12 0]))
    (are [i o] (= (bytes->uint i) o)
      [1 2] 513
      [255 254] (-> 254 (* 256) (+ 255)))
    (are [i o] (= (uint->bytes i 2) o)
      513 [1 2]
      (-> 254 (* 256) (+ 255)) [255 254])

    (is (nil? (int->bytes nil 0)))
    (is (= (int->bytes -12 2) [244 255]))
    (are [i o] (= (bytes->int i) o)
      [1 2] 513
      [254 255] -2)
    (are [i o] (= (int->bytes i 2) o)
      513 [1 2]
      -2 [254 255])

    (are [i o] (= (bcd+->uint i) o)
      [0x12 0x99] 9912)
    (are [i o] (= (uint->bcd+ i 2) o)
      9912 [0x12 0x99]
      5612 [0x12 0x56])

    (are [i o] (= (bcd+->int i) o)
      [0x12 0x99] -1912)
    (are [i o] (= (int->bcd+ i 2) o)
      -1912 [0x12 0x99])))
